<template>
  <div id="TraceabilityChart" class="chart" ref="chartRef"></div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, onUnmounted } from 'vue';
import * as echarts from 'echarts';

export default defineComponent({
  name: 'TraceabilityChart',
  setup() {
    const chartRef = ref<HTMLDivElement | null>(null); // 使用 ref 获取 DOM 节点
    let chart: echarts.ECharts | null = null;

    const initChart = () => {
      if (chartRef.value) {
        chart = echarts.init(chartRef.value);

        const option = {
          grid: {
            top: 30,
            right: 20,
            bottom: 30,
            left: 30,
          },
          xAxis: {
            type: 'category',
            data: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], // 月份
            axisLabel: {
              rotate: 20, // 倾斜 20 度
              textStyle: {
                fontSize: 12,
              },
            },
            axisTick: {
              show: false,
            },
          },
          yAxis: {
            name: '溯源次数',
            type: 'value',
            min: 0,
            max: 300,
            interval: 50,
            splitLine: {
              lineStyle: {
                type: 'dashed',
              },
            },
            axisTick: {
              show: false,
            },
          },
          series: [
            {
              name: '实际溯源次数',
              data: [175, 125, 90, 130, 145, 165, 150, 170, 190, 200, 215, 230],
              type: 'bar',
              itemStyle: {
                color: '#5470c6',
              },
              emphasis: {
                itemStyle: {
                  color: '#91cc75',
                },
              },
            },
            {
              name: '目标溯源次数',
              data: [160, 140, 120, 110, 100, 80, 70, 90, 110, 130, 150, 170],
              type: 'line',
              smooth: true,
              lineStyle: {
                color: '#fac858',
                width: 2,
              },
              itemStyle: {
                color: '#fac858',
              },
            },
          ],
        };

        chart.setOption(option);
      }
    };

    const handleResize = () => {
      if (chart) {
        chart.resize(); // 图表自适应容器大小
      }
    };

    onMounted(() => {
      initChart();

      // 监听窗口大小变化
      window.addEventListener('resize', handleResize);
    });

    onUnmounted(() => {
      // 销毁图表实例并清理事件监听器
      if (chart) {
        chart.dispose();
        chart = null;
      }
      window.removeEventListener('resize', handleResize);
    });

    return {
      chartRef,
    };
  },
});
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
